import {Stage, Layer, Image, Rect} from 'react-konva';
import useImage from "use-image";
import KonvaText, {KonvaTextType} from "@/components/konva/konva-text";
import {useRef, useState} from "react";

interface KonvaDataType {
    background?: {
        backgroundImage?: string;
        width: number;
        height: number;
    };
    content?: Array<{
        type: string;
        id: string;
        text?: KonvaTextType

    }>;
}

function Canvas({defaultValue}: { defaultValue?: KonvaDataType }) {
    const [image] = useImage(defaultValue?.background?.backgroundImage as string);
    const stageRef = useRef(null);

    const [selectId, setSelectId] = useState<string | null>(null);
    const [scale,setScale] = useState<number>(1);
    return (
        <Stage
            ref={stageRef}
            width={window.innerWidth}
            height={window.innerHeight}
            scaleX={scale}
            scaleY={scale}
            onWheel={(e)=>{
               if (scale + 0.01 * e.evt.deltaY > 0.1 && scale + 0.01 * e.evt.deltaY < 2) setScale(scale + 0.01 * e.evt.deltaY)
            }}
        >

            <Layer onClick={() => {
                setSelectId(null)
            }}>
                <Rect
                    width={defaultValue?.background?.width || 500}
                    height={defaultValue?.background?.height || 300}
                    // fill="rgba(0, 0, 0, 0)"
                    fill="rgba(255, 255, 255, 1)"
                />
                <Image
                    image={image}
                    alt=""
                    width={defaultValue?.background?.width || 500}
                    height={defaultValue?.background?.height || 300}
                />
            </Layer>
            {
                defaultValue?.content?.map((item) => {
                    return (
                        <KonvaText
                            key={item.id}
                            data={item?.text}
                            isSelected={selectId == item.id}
                            onKonvaClick={() => {
                                setSelectId(item.id);
                            }}
                        />
                    )

                })
            }

        </Stage>
    );
}

export default Canvas;